import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author: knowno
 * @create: 2025-09-18 09:04
 * @Version 1.0
 **/
public class TestJDBC_Trans {
    public static void main(String[] args) {

        //订单 => 订单表(insert),订单详情表(insert),账号余额(update),商品库存(update) ->整体成功，否则回滚

        //转账 => 转出账号  转入账号  金额 => 转出账号金额减少(update)，转入账号金额增加(update)  -> 整体成功，否则回滚

        //充值=> 公交卡充值: 支付,  请勿取卡,充值中.. 倒计时,才充值

        //模拟转账的事务处理
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {
            conn = DBUtil.getConn();
            //开启事务
            conn.setAutoCommit(false);
            //转账的sql语句
            String sql = "update account set money=money-100 where id=1";
            //转出账号金额减少
            preparedStatement = conn.prepareStatement(sql);
            int result1 = preparedStatement.executeUpdate();

            System.out.println(1/0);

            sql = "update account set money=money+100 where id=2";
            //转入账号金额增加
            preparedStatement = conn.prepareStatement(sql);
            int result2 = preparedStatement.executeUpdate();
            if (result1 != 1 || result2 != 1) {
                throw new Exception("转账失败");
            }

            //提交事务
            conn.commit();
            System.out.println("转账成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //回滚事务
            try {
                conn.rollback();
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            System.out.println("转账失败");
        }


    }
}
